package model

import (
	"encoding/base64"
	"ginblog/utils/errmsg"
	"github.com/jinzhu/gorm"
	"golang.org/x/crypto/scrypt"
	"log"
)

type User struct {
	gorm.Model
	Username string `gorm:"type:varchar(20);not null" json:"username" validate:"required,min=3,max=16" label:"用户名"`
	Password string `gorm:"type:varchar(20);not null" json:"password" validate:"required,min=6,max=16" label:"密码"`
	Role     int    `gorm:"type:int;DEFAULT:2" json:"role" validate:"required,gte=2" label:"角色码"`
}

//查询用户是否存在
func CheckUser(username string)(code int) {
	var user User
	db.Debug().Where("username = ?", username).First(&user)
	if user.ID  != 0 {
		return errmsg.ERROR_USERNAME_USED
	} else {
		return errmsg.SUCCESS
	}
}

//新增用户
func CreateUser(data *User) int {
	data.Password = ScryptPwd(data.Password)
	err := db.Debug().Create(&data).Error
	if err != nil {
		return errmsg.ERROR //500
	}
	return errmsg.SUCCESS //200
}

//根据username查询user信息
func SelectByName(username string)(int, User){
	var user User
	err := db.Debug().Where("username = ?", username).First(&user).Error
	if err != nil {
		return errmsg.ERROR, user
	}
	return errmsg.SUCCESS, user

}

//查询所有用户
func SelectUsers() ([]User, int) {
	var users []User
	err := db.Debug().Find(&users).Error
	if err != nil && err != gorm.ErrRecordNotFound{
		return nil, errmsg.ERROR
	}
	return users, errmsg.SUCCESS
}

//删除用户
func DeleteUser(id int) int {
	var user User
	err := db.Where("id = ?", id).Delete(&user).Error
	if err != nil {
		return errmsg.ERROR
	}
	return errmsg.SUCCESS
}

//编辑用户
func Edituser(id int, data *User) int {
	var user User
	var UserMap = make(map[string]interface{})
	UserMap["username"] = data.Username
	UserMap["role"] = data.Role
	err := db.Debug().Model(&user).Where("id = ?", id).Updates(UserMap).Error
	if err != nil {
		return errmsg.ERROR
	}
	return errmsg.SUCCESS
}

//密码加密
func ScryptPwd(password string) string {
	const KeyLen =10
	salt := make([]byte, 8)
	salt = []byte{12,32,4,6,33,21,25,96}
	HashPwd, err := scrypt.Key([]byte(password), salt, 1024, 8, 1, KeyLen)
	if err != nil {
		log.Fatal(err)
	}
	fpw := base64.StdEncoding.EncodeToString(HashPwd)
	return fpw
}

//登陆
func CheckLogin(username string, password string) int {
	var user User
	err := db.Debug().Where("username = ?", username).First(&user).Error
	if err != nil {
		return errmsg.ERROR_USER_NOT_EXIST
	}
	if ScryptPwd(password) != user.Password {
		return errmsg.ERROR_PASSWORD_WRONG
	}
	if user.Role < 2 {
		return errmsg.ERROR_USER_NO_RIGHT
	}
	return errmsg.SUCCESS
}